package com.ecric.sensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;

public class CompassActivity extends AppCompatActivity implements SensorEventListener {

    private ImageView img_com;
    private SensorManager sm;
    private List<Sensor> deviceSensors;
    /**方向传感器*/
    private Sensor orientation;
    /** 记录指南针图片旋转过的角度*/
    float  currentDegree = 0f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);
        img_com = (ImageView) findViewById(R.id.img_com);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        //获取手机上支持的所有传感器
        deviceSensors = sm.getSensorList(Sensor.TYPE_ALL);
        if (!check(Sensor.TYPE_ORIENTATION)) {
            Toast.makeText(this, "当前设备不支持方向传感器", Toast.LENGTH_SHORT).show();
        }else {
            orientation = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (orientation != null){
            sm.registerListener(this,orientation,SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        switch (event.sensor.getType()){
            case Sensor.TYPE_ORIENTATION:
                //获取绕Z轴旋转角度
                float  degreeZ = event.values[0];
                //创建旋转动画
                RotateAnimation ra =  new RotateAnimation(currentDegree,-degreeZ,
                        Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
                ra.setDuration(200);
                img_com.startAnimation(ra);
                currentDegree  = - degreeZ ;
                break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


    /**
     * 检测设备是否支持某类型的传感器
     *
     * @param type 传感器的类型
     * @return true  当前设备支持该类型的传感器  否则不支持
     */
    private boolean check(int type) {
        Iterator<Sensor> iterator = deviceSensors.iterator();
        while (iterator.hasNext()) {
            Sensor sensor = iterator.next();
            if (sensor.getType() == type) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (orientation != null){
            sm.unregisterListener(this);
        }
    }

}